<template>
  <div class="base-table-content">
    <a-button class="fr mb8" @click="handleAdd">
      <PlusOutlined />
      新增
    </a-button>
    <a-table
      :columns="columns"
      :data-source="tableData"
      bordered
      @change="handleTableChange"
      :loading="loading"
      :pagination="pagination"
      rowKey="menuId"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'perms'">
          <div>
            <a-input
              v-if="column[record.menuId]"
              v-model:value="column[record.menuId][column.dataIndex]"
              style="margin: -5px 0"
            />
            <template v-else> {{ record.perms }} </template>
          </div>
        </template>
        <template v-if="column.dataIndex === 'operate'">
          <div class="editable-row-operations">
            <span v-if="column[record.menuId]">
              <a-typography-link @click="handleAdd(record.parentId)">新增</a-typography-link>
              <a-popconfirm title="确认删除?" @confirm="handlerDelete(record.menuId)">
                <a>删除</a>
              </a-popconfirm>
            </span>
            <span v-else>
              <a @click="handleEdit(record)">编辑</a>
            </span>
          </div>
        </template>
      </template>
    </a-table>
  </div>
  <a-drawer
    v-model:open="open"
    class="custom-class"
    root-class-name="root-class-name"
    :title="drawTitle"
    placement="right"
    :closable="false"
    width="500"
  >
    <a-form
      ref="formRef"
      :model="formState"
      name="basic"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 16 }"
      autocomplete="off"
    >
      <a-form-item label="所属菜单" name="menuIds">
        <a-cascader v-model:value="formState.menuIds" :options="menuArr" change-on-select />
      </a-form-item>
      <a-form-item
        label="菜单名称"
        name="menuName"
        :rules="[{ required: true, message: '请输入菜单名称!' }]"
      >
        <a-input v-model:value="formState.menuName" />
      </a-form-item>
      <a-form-item label="菜单类型" name="menuType" :rules="[{ required: true }]">
        <a-radio-group v-model:value="formState.menuType">
          <a-radio value="M">目录</a-radio>
          <a-radio value="C">菜单</a-radio>
          <a-radio value="F">按钮</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item
        label="菜单路径"
        name="path"
        :rules="[{ required: true, message: '请输入菜单路径!' }]"
        v-if="formState.menuType === 'C'"
      >
        <a-input v-model:value="formState.path" />
      </a-form-item>
      <a-form-item
        label="权限标识"
        name="perms"
        :rules="[{ required: true, message: '请输入权限标识!' }]"
        v-if="formState.menuType === 'F'"
      >
        <a-input v-model:value="formState.perms" />
      </a-form-item>
      <a-form-item
        label="菜单图标"
        name="iconName"
        :rules="[{ required: true, message: '请输入菜单图标!' }]"
        v-if="formState.menuType === 'M'"
      >
        <a-input v-model:value="formState.iconName" />
      </a-form-item>
      <a-form-item label="菜单状态" name="status" :rules="[{ required: true }]">
        <a-switch v-model:checked="formState.status" :checkedValue="0" :unCheckedValue="1" />
      </a-form-item>
      <a-form-item
        label="显示顺序"
        name="orderNum"
        :rules="[{ required: true, message: '请输入显示顺序!' }]"
      >
        <a-input v-model:value="formState.orderNum" />
      </a-form-item>
    </a-form>
    <template #footer>
      <a-button key="back" style="margin-right: 16px" @click="closeDrawer">取消</a-button>
      <a-button key="submit" type="primary" @click="handleSubmit">提交</a-button>
    </template>
  </a-drawer>
</template>

<script setup lang="ts">
import { FormOutlined, DeleteOutlined, PlusOutlined } from '@ant-design/icons-vue'
import { getMenuList, addMenu, editMenu, deleteMenu, getMenu } from '@/apis/system/menu'
import { message, type TreeProps } from 'ant-design-vue'
import { useFetchList } from '@/hooks/table/useFetchList'
import { columns } from './consts/tableColumns'

const formRef = ref()
let open = ref<boolean>(false)
let drawTitle = ref<string>('新增菜单')

const query = reactive({
  menuName: ''
})

const { tableData, handleSearch, initTable, handleTableChange, pagination, loading } = useFetchList(
  getMenuList,
  query
)
const transformTree = (tree: any) => {
  return tree.map((node: any) => {
    const isPermission = node.children && node.children.find((item: any) => item.menuType === 'F')
    return {
      label: node.name,
      value: node.menuId,
      menuType: node.menuType,
      parentId: node.parentId,
      children: node.children && !isPermission ? transformTree(node.children) : undefined // 递归处理子节点
    }
  })
}
const menuArr = ref<any[]>([])
const handleTransformMenus = () => {
  menuArr.value = transformTree(tableData.value)
}
onMounted(() => {
  handleSearch()
})
const handleGetMenuIds = (menuId: string | number) => {
  let menuIds = [] as any[]
  const findItem = (currentParentId: string | number, menus: any[]) => {
    for (const item of menus) {
      if (item.value === menuId) {
        currentParentId && menuIds.unshift(currentParentId)
        if (!item.children) {
          menuIds.push(item.value)
        }
      }
      if (item.children) {
        findItem(item.value, item.children)
      }
    }
  }
  findItem(menuId, menuArr.value)
  return menuIds
}
const handleAdd = (parentId: number) => {
  handleTransformMenus()
  drawTitle.value = '新增菜单'
  open.value = true
}

const handleEdit = (record: any) => {
  handleTransformMenus()
  drawTitle.value = '编辑菜单'
  open.value = true
  formState = {
    menuId: record.menuId,
    menuName: record.name,
    parentId: record.parentId,
    orderNum: record.orderNum,
    path: record.path,
    component: record.component,
    isFrame: record.isFrame,
    menuType: record.menuType,
    visible: record.visible,
    status: record.status,
    perms: record.perms,
    iconName: record.iconName,
    remark: record.remark,
    menuIds: handleGetMenuIds(record.menuId)
  }
}

const handlerDelete = async (menuId: string | number) => {
  const res = await deleteMenu({ menuId })
  if (res.code === 200) {
    message.success('删除成功')
    handleSearch()
    return
  }
  message.error('删除失败')
}

const handleSubmit = () => {
  formRef.value
    .validate()
    .then(async () => {
      console.log('values', formState)
      const fn = formState.menuId ? editMenu : addMenu
      const len = formState.menuIds.length
      const res = await fn({
        ...formState,
        path: formState.menuType === 'C' ? formState.path : '',
        iconName: formState.menuType === 'M' ? formState.iconName : '',
        perms: formState.menuType === 'F' ? formState.perms : '',
        parentId: len ? formState.menuIds[len - 1] : 0,
        menuIds: undefined
      })
      if (res.code === 200) {
        message.success('操作成功！')
        closeDrawer()
        formState.menuId ? handleSearch() : initTable()
        return
      }
      message.error('操作失败！')
    })
    .catch(() => {
      console.log('error')
    })
}

const closeDrawer = () => {
  formRef.value.resetFields()
  formState = reactive({
    menuId: '',
    menuName: '',
    parentId: '',
    orderNum: 1,
    path: '',
    component: '',
    isFrame: 1,
    menuType: 'M',
    visible: 0,
    status: 0,
    perms: '',
    iconName: '',
    remark: '',
    menuIds: [] as any[]
  })
  open.value = false
}

interface FormState {
  menuId?: string | number
  menuName: string
  parentId: number | string
  orderNum: number
  path: string
  component: string
  isFrame: number
  menuType: string
  visible: number
  status: number
  perms: string
  iconName: string
  remark: string
  menuIds: any[]
}
let formState = reactive<FormState>({
  menuId: '',
  menuName: '',
  parentId: '',
  orderNum: 1,
  path: '',
  component: '',
  isFrame: 1,
  menuType: 'M',
  visible: 0,
  status: 0,
  perms: '',
  iconName: '',
  remark: '',
  menuIds: [] as any[]
})
</script>

<style scoped>
.editable-row-operations a {
  margin-right: 8px;
}
</style>
